package com.gdhengdian.map._interface._impl;

import com.gdhengdian.map._interface.Map;
import org.w3c.dom.Node;

import java.util.Objects;

/**
 * 基于链表实现的Map
 * @author HD-0078 杨炜耀
 * @date 2021-4-8 15:50
 */
public class LinkedListMap<K, V> implements Map<K, V> {

    /**
     * 虚拟头节点
     */
    private final Node dummyHead;

    /**
     * 元素个数
     */
    private int size;

    public LinkedListMap(){
        this.dummyHead = new Node();
        size = 0;
    }


    @Override
    public void put(K key, V value) {
        Node node = getNode(key);
        if(node == null){
            // key不存在，往链表的头部插入新元素
            dummyHead.next = new Node(key, value, dummyHead.next);
            size++;
        }else {
            node.value = value;
        }
    }

    @Override
    public V remove(K key) {
        Node prev = dummyHead;
        while (prev.next != null){
            // 根据key找到待删除节点的前一个节点
            if(prev.next.key.equals(key)){
                break;
            }
            prev = prev.next;
        }
        if(prev.next != null){
            Node delNode = prev.next;
            prev.next = delNode.next;
            delNode.next = null;
            size--;
            return delNode.value;
        }
        return null;
    }

    @Override
    public boolean contains(K key) {
        return getNode(key) != null;
    }

    @Override
    public V get(K key) {
        Node node = getNode(key);
        return node == null ? null : node.value;
    }

    @Override
    public void set(K key, V value) {
        Node node = getNode(key);
        if(node == null){
            throw new IllegalArgumentException(key + "doesn't exist!");
        }
        node.value = value;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }


    private Node getNode(K key){
        Node currentNode = dummyHead.next;
        while (currentNode != null){
            if(currentNode.key.equals(key)){
                return currentNode;
            }
            currentNode = currentNode.next;
        }
        return null;
    }

    /**
     * 链表的节点结构，节点中会存储键值对，而不是单个元素
     */
    private class Node {
        K key;
        V value;
        Node next;

        public Node(K key, V value, Node next){
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public Node(K key, V value) {
            this(key, value, null);
        }

        public Node() {
            this(null, null, null);
        }
    }

}
